﻿using AutoMapper;

using Microsoft.IdentityModel.Tokens;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using ZFB.Common;
using ZFB.DTO;
using ZFB.IServices;
using ZFB.Models;
using ZFB.Repository.AdminUser;
using ZFB.Repository.City;
using ZFB.Repository.User;

namespace ZFB.Services
{
    public class UserServices : IUserServices
    {
        private readonly IUserRepository _userRepository;
        private readonly ICityRepository cityRepository;
        private readonly IMapper mapper;
        public UserServices(IUserRepository userRepository, IMapper mapper, ICityRepository cityRepository)
        {
            _userRepository = userRepository;
            this.mapper = mapper;
            this.cityRepository = cityRepository;
        }

        public async Task<ApiResult> AddNewAsync(string phoneNum, string password)
        {
            if (await _userRepository.IsExistAsync(e => e.PhoneNum == phoneNum)) return new ApiResult("账号已存在");
            var salt = CommonHelper.CreateVerifyCode(8);
            var psw = CommonHelper.CalcMD5(password + salt);
            var res = await _userRepository.AddAsync(new T_Users
            {
                PhoneNum = phoneNum,
                PasswordHash = psw,
                PasswordSalt = salt
            });
            return res <= 0 ? new ApiResult("注册失败！") : new ApiResult();
        }

        public async Task<ApiResult> CheckLoginAsync(string phoneNum, string password)
        {
            var user = await _userRepository.GetModelAsync(e => e.PhoneNum == phoneNum);
            if (user == null) return new ApiResult("账号不存在");
            var psd = CommonHelper.CalcMD5(password + user.PasswordSalt);
            if (user.PasswordHash == psd)
            {
                //JWT

                return new ApiResult("登录成功");
            }
            return new ApiResult("账号或密码错误");
        }

        public async Task<ApiResult> GetById(long id)
        {
            var data = await _userRepository.GetModelAsync(e => e.Id == id);

            if (data==null)
            {
                return new ApiResult("用户不存在!");
            }
            else
            {
                var dto = mapper.Map<UserDTO>(data);
                return new ApiResult(dto);
            }
        }

        public async Task<ApiResult> GetByPhoneNumAsync(string phoneNum)
        {
            var data = await _userRepository.GetListAsync(e => e.PhoneNum == phoneNum);

            if (data.IsNullOrEmpty())
            {
                return new ApiResult("用户不存在!");
            }
            else if (data.Count > 1)
            {
                throw new ApplicationException($"存在多条手机号{phoneNum}");
            }
            else
            {
                var dto = mapper.Map<List<UserDTO>>(data);
                return new ApiResult(dto);
            }
        }

        public async Task<ApiResult> SetUserCityIdAsync(long userId, long cityId)
        {
            var data = await _userRepository.GetModelAsync(e => e.Id == userId);

            if (data == null)
            {
                return new ApiResult("用户不存在!");
            }
            else 
            {
                if (!await cityRepository.IsExistAsync(e => e.Id == cityId))
                    return new ApiResult("城市不存在");
                data.CityId = cityId;
               await _userRepository.UpdateAsync(data);
                return new ApiResult();
            }
        }

        public async  Task<ApiResult> UpdatePwdAsync(string phoneNum, string newPassword)
        {
            var data = await _userRepository.GetModelAsync(e => e.PhoneNum == phoneNum);
            if (data == null)
                return new ApiResult("用户不存在");
            var salt = CommonHelper.CreateVerifyCode(8);
            data.PasswordHash = CommonHelper.CalcMD5(newPassword + salt);
            data.PasswordSalt = salt;
            var newdata = await _userRepository.UpdateAsync(data);
            return newdata <= 0 ? new ApiResult("修改失败！") : new ApiResult();
        }
    }
}
